package zl.osimall.manager.controller;

import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import zl.osimall.common.bean.Goods;
import zl.osimall.common.bean.RespBean;
import zl.osimall.common.bean.option1Vo;
import zl.osimall.common.exception.SteduException;
import zl.osimall.common.service.GoodsService;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;
    @Value("${zl.uploaddir}")
    public String uploaddir;

    @GetMapping("/page")
    public RespBean selectConditionByPage(Goods condition,
                                          Integer pageNum, Integer pageSize) {
        PageInfo<Goods> pageInfo = goodsService.selectByLike(condition, pageNum, pageSize);
        return RespBean.ok("查询成功", pageInfo);
    }

    @GetMapping("/count")
    public RespBean selectByCount() {
        List<Goods> list = goodsService.selectByCount();
        List<String> list1 =new ArrayList<>();
        List<Integer> list2 = new ArrayList<>();
        for (Goods goods : list) {
            list1.add(goods.getName());
            list2.add(goods.getCount());
        }
        return RespBean.ok("查询成功", new option1Vo(list1,list2));
    }

    @GetMapping("/{id}")
    public RespBean selectById(@PathVariable("id") Integer id) throws SteduException{
        return RespBean.ok("查询成功", goodsService.selectById(id));
    }

    @PostMapping
    public RespBean add(@RequestBody Goods goods) throws SteduException {
        if (goods.getPicList().isEmpty()){
            return RespBean.error("图片不能为空");
        }
        goodsService.add(goods);
        return RespBean.ok("添加成功");
    }

    @DeleteMapping("/{id}")
    public RespBean delete(@PathVariable("id") Integer id) throws SteduException {
        goodsService.delete(id);
        return RespBean.ok("删除成功");
    }

    @PutMapping
    public RespBean update(@RequestBody Goods goods) throws SteduException {
        goodsService.update(goods);
        return RespBean.ok("修改成功");
    }

}
